package com.dfish.downloadtoolNew;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Method;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.RemoteException;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.android.internal.telephony.ITelephony;
import com.dfish.downloadtool.util.CheckVersionBean;
import com.dfish.downloadtool.util.MyDownloadToolHttp;
import com.dfish.downloadtool.util.ProgressControl;
import com.yuhanxun.util.AppGlobalVariable;
import com.yuhanxun.util.DealFile;
import com.yuhanxun.util.DealHttp;
import com.yuhanxun.util.DealPreferences;

public class MainActivity extends Activity implements View.OnClickListener {
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == UNINSTALL_REQUEST) {
			if (!AppGlobalVariable.hasThatApk(this, UNINSTALL_PACKAGE_NAME)) {
				Toast.makeText(this, "更新已成功完成", Toast.LENGTH_SHORT).show();
			}
		}
	}

	private MyService mService;
	private boolean mIsServiceBinded;
	private String mPhoneNum;
	private Button mButtonsetupRtsp;
	private Button mButtonStopRtsp;
	private Button mButtonCheckAppVer;
	private ProgressBar mProgressBar;
	private EditText mTotalDataEditText;
	private TextView rtspResultView;
	private EditText mThreadNumber;
	private TextView mPhoneNumberTextView;
	private EditText mDownloadTimeEditText;

	private static final int START_THREAD = 0;
	private static final int CACULATE_DATA = 1;
	private static final int HAND_OFF = 2;
	private static final int USE_TIME = 3;

	private static final String CHECK_APP_VER_URL = "http://112.124.59.79/new_apx.xml";
	private static final String Address_URL = "http://112.124.59.79/address";

	private static final int START_CHECK = 0;
	private static final int START_DOWNLOAD = 1;
	private static final int START_INSTALL = 2;
	private static final int NETWORK_ERROR = 3;
	private static final int GET_ADDRESS_WEB_OK = 4;
	private static final int GET_ADDRESS_WEB_FAIL = 5;
	private static final int GET_ADDRESS_LOCAL_OK = 6;

	public static final String RTSP_NAME = "rstp";
	public static final String RTSP_TOTAL = "rtsp_total";
	public static final String DOWNLOAD_TIME = "download_time";
	public static final String STOP_MUSIC = "stop_music";
	public static final String TOTAL_TIME = "total_time";

	public static long mDownloadData;
	public static byte[] lock = new byte[0];
	private ITelephony iTelephony;
	private TelephonyManager manager;
	private int mUrlPoint = 0;
	private IntentFilter intentFilter;
	private boolean isRegister = false;

	private static int mDownloadTime = 0;

	private static int mTotalTime;
	private TextView mUseTimeTextView;

	private static String mTotalDataString; // 阀值总量
	public static long mMaxData = -1L;
	public static boolean isRunning = false;
	public static int UNINSTALL_REQUEST = 0;
	public static String UNINSTALL_PACKAGE_NAME = "com.dfish.downloadtool";

	private BroadcastReceiver mTimeReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			if (Intent.ACTION_TIME_TICK.equals(action)) {
				mDownloadTime = DealPreferences.readIntPreferences(RTSP_NAME, DOWNLOAD_TIME, MainActivity.this);
				if (mDownloadTime >= mTotalTime) {
					isRunning = false;
					mService.closeRtsp();
					mService.gameOver();
					if (isRegister) {
						unregisterReceiver(mTimeReceiver);
						isRegister = false;
					}
				} else {
					mDownloadTime++;
					DealPreferences.writeIntPreferences(RTSP_NAME, DOWNLOAD_TIME, mDownloadTime, MainActivity.this);
					handler.sendEmptyMessage(USE_TIME);
				}
			}
		}
	};

	private static String[] sUrlList = {
			"rtsp://vod01.v.vnet.mobi/00000018/20120918/10140000000180000000018892443001/00000018_10140000000180000000018892460001_150MP4QVGA.3gp",
			"rtsp://vod01.v.vnet.mobi/00000018/20120920/10142000000180000000018972880001/00000018_10142000000180000000018972894001_150MP4QVGA.3gp",
			"rtsp://vod01.v.vnet.mobi/00000018/20120920/10142000000180000000018972881001/00000018_10142000000180000000018972896001_150MP4QVGA.3gp",
			"rtsp://vod01.v.vnet.mobi/00000018/20120920/10142000000180000000018972882001/00000018_10142000000180000000018972898001_150MP4QVGA.3gp",
			"rtsp://vod01.v.vnet.mobi/00000097/20120926/10145000000970000000019132893001/00000097_10145000000970000000019132982001_150MP4QVGA.3gp",
			"rtsp://vod01.v.vnet.mobi/00000097/20120926/10145000000970000000019132894001/00000097_10145000000970000000019132984001_150MP4QVGA.3gp",
			"rtsp://vod01.v.vnet.mobi/00000097/20120926/10145000000970000000019132895001/00000097_10145000000970000000019132986001_150MP4QVGA.3gp",
			"rtsp://vod01.v.vnet.mobi/00000018/20120918/10140000000180000000018892441001/00000018_10140000000180000000018892456001_150MP4QVGA.3gp",
			"rtsp://vod01.v.vnet.mobi/00000018/20120918/10140000000180000000018892442001/00000018_10140000000180000000018892458001_150MP4QVGA.3gp",
			"rtsp://vod01.v.vnet.mobi/00000018/20120918/10140000000180000000018892443001/00000018_10140000000180000000018892460001_150MP4QVGA.3gp" 
			
	};

	public void phoner() {
		manager = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
		Class<TelephonyManager> c = TelephonyManager.class;
		Method getITelephonyMethod = null;
		try {
			getITelephonyMethod = c.getDeclaredMethod("getITelephony", (Class[]) null);
			getITelephonyMethod.setAccessible(true);
			iTelephony = (ITelephony) getITelephonyMethod.invoke(manager, (Object[]) null);
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mDownloadData = DealPreferences.readLongPreferences(RTSP_NAME, RTSP_TOTAL, this);

		// YUHANXUN 设置lable版本号
		double localVer = Double.parseDouble(AppGlobalVariable.getAppVersionName(MainActivity.this));
		setTitle(getResources().getString(R.string.app_name) + "_v" + String.valueOf(localVer));

		setContentView(R.layout.activity_main);
		TelephonyManager mTelephonyMgr;
		mTelephonyMgr = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
		mPhoneNum = mTelephonyMgr.getLine1Number();
		DDebug.logd("mPhoneNum = " + mPhoneNum);

		mButtonStopRtsp = (Button) findViewById(R.id.rtsp_stop);
		mButtonStopRtsp.setOnClickListener(this);
		rtspResultView = (TextView) findViewById(R.id.rtsp_resultView);
		mThreadNumber = (EditText) findViewById(R.id.threads_num);
		mThreadNumber.setText("30");
		((Button) findViewById(R.id.clear_record)).setOnClickListener(this);
		((Button) findViewById(R.id.stop_music)).setOnClickListener(this);
		mButtonsetupRtsp = (Button) findViewById(R.id.rtsp_setup);
		mButtonsetupRtsp.setOnClickListener(this);
		mPhoneNumberTextView = (TextView) this.findViewById(R.id.phone_number);
		mTotalDataEditText = (EditText) findViewById(R.id.total_data);
		mTotalDataEditText.setText("1000");
		mDownloadTimeEditText = (EditText) findViewById(R.id.download_time);
		((Button) findViewById(R.id.dial_number)).setOnClickListener(this);
		mUseTimeTextView = (TextView) findViewById(R.id.use_time);
		mButtonCheckAppVer = (Button) findViewById(R.id.check_appver_btn);
		mButtonCheckAppVer.setOnClickListener(this);
		mProgressBar = (ProgressBar) findViewById(R.id.check_appver_pro);
		phoner();

		intentFilter = new IntentFilter();
		intentFilter.addAction(Intent.ACTION_TIME_TICK);
		setResultView(mDownloadData);
		handler.sendEmptyMessageDelayed(CACULATE_DATA, 2000);

		// YUHANXUN
		uninstall(this, UNINSTALL_PACKAGE_NAME);
		startCheckVerThread();
		// local address
		if (startGetLocalAddress()) {
			checkVerHandler.obtainMessage(GET_ADDRESS_LOCAL_OK).sendToTarget();
		} else {
			// web address
			if (DealHttp.isConnectInternet(this)) {
				startGetAddressThread();
			} else {
				checkVerHandler.obtainMessage(GET_ADDRESS_WEB_FAIL).sendToTarget();
			}
		}

	}

	private void setResultView(long data) {
		long mm = data / 1048576;
		long mmy = data % 1048576;
		long kk = mmy / 1024;
		long bb = mmy % 1024;
		rtspResultView.setText("当前下载量为" + mPhoneNum + ":" + mm + "M" + kk + "K" + bb + "B");
	}

	public void onStart() {
		super.onStart();

		if (null == startService(new Intent(MainActivity.this, MyService.class))) {
			return;
		}
		mIsServiceBinded = bindService(new Intent(MainActivity.this, MyService.class), mServiceConnection, Context.BIND_AUTO_CREATE);
		if (!mIsServiceBinded) {
			finish();
			return;
		}
	}

	public void onResume() {
		super.onResume();
	}

	public void onPause() {
		super.onPause();
	}

	public void onStop() {
		mService.closeRtsp();
		if (mIsServiceBinded) {
			unbindService(mServiceConnection);
			mIsServiceBinded = false;
		}
		super.onStop();
	}

	private final ServiceConnection mServiceConnection = new ServiceConnection() {
		public void onServiceConnected(ComponentName className, IBinder service) {
			DDebug.logd("mService");
			mService = ((MyService.MyBinder) service).getService();
		}

		public void onServiceDisconnected(ComponentName className) {
			DDebug.logd("mService is null");
			mService = null;
		}
	};

	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (isRegister) {
			unregisterReceiver(mTimeReceiver);
			isRegister = false;
		}
		DealFile.delAllFile(AppGlobalVariable.getDIR_DOWNLOAD());
	}

	public void onClick(View v) {
		int id = v.getId();
		switch (id) {
		case R.id.rtsp_setup:
			isRunning = true;
			DealPreferences.writeBooleanPreferences(RTSP_NAME, STOP_MUSIC, false, this);
			if (AppGlobalVariable.checkNetWork(this)) {
				handler.sendEmptyMessage(START_THREAD);
				mButtonsetupRtsp.setEnabled(false);
				mTotalDataEditText.setEnabled(false);
				mThreadNumber.setEnabled(false);
				mDownloadTimeEditText.setEnabled(false);
			} else {
				Toast.makeText(MainActivity.this, "请打开网络链接后重试！", Toast.LENGTH_SHORT).show();
			}

			String time = mDownloadTimeEditText.getText().toString().trim();
			if (!TextUtils.isEmpty(time)) {
				mTotalTime = Integer.parseInt(time);
				registerReceiver(mTimeReceiver, intentFilter);
				isRegister = true;
				mDownloadTime = DealPreferences.readIntPreferences(RTSP_NAME, DOWNLOAD_TIME, this);
				mUseTimeTextView.setText(" 已下载：" + mDownloadTime + "分钟");
			}

			handler.sendEmptyMessage(USE_TIME);
			break;
		case R.id.rtsp_stop:
			isRunning = false;
			mService.closeRtsp();
			mButtonsetupRtsp.setEnabled(true);
			if (isRegister) {
				unregisterReceiver(mTimeReceiver);
				isRegister = false;
			}
			break;
		case R.id.clear_record:
			// 程序正在跑的时候不能清除数据
			if (!isRunning) {
				DDebug.logd("clear data");
				mDownloadData = 0;
				DealPreferences.writeLongPreferences(MainActivity.RTSP_NAME, MainActivity.RTSP_TOTAL, 0L, this);
				mDownloadTime = 0;
				mTotalTime = 0;
				DealPreferences.writeBooleanPreferences(RTSP_NAME, STOP_MUSIC, false, this);
				DealPreferences.writeIntPreferences(RTSP_NAME, DOWNLOAD_TIME, 0, this);

				if (!mTotalDataEditText.isEnabled()) {
					mTotalDataEditText.setEnabled(true);
				}

				if (!mThreadNumber.isEnabled()) {
					mThreadNumber.setEnabled(true);
				}

				if (!mDownloadTimeEditText.isEnabled()) {
					mDownloadTimeEditText.setEnabled(true);
				}
			}
			break;
		case R.id.stop_music:
			DDebug.logd("stop music");
			mService.stopPlaying();
			DealPreferences.writeBooleanPreferences(RTSP_NAME, STOP_MUSIC, true, this);
			break;
		case R.id.dial_number:
			String phoneNumber = mPhoneNumberTextView.getText().toString();
			if (!TextUtils.isEmpty(phoneNumber)) {
				Uri localUri = Uri.parse("tel:" + phoneNumber);
				Intent call = new Intent(Intent.ACTION_CALL, localUri);
				call.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				startActivity(call);
			}
			handler.sendEmptyMessageDelayed(HAND_OFF, 45 * 1000);
			// String apkPath = AppGlobalVariable.getDIR_DOWNLOAD() +
			// "DownLoadToo11l.apk";
			// String apkPath = this.
			// try {
			// String command = "chmod 777 " + apkPath;
			// Runtime runtime = Runtime.getRuntime();
			// Process proc = runtime.exec(command);
			// } catch (IOException e) {
			// e.printStackTrace();
			// }
			// DealFile.openFile(new File(apkPath), MainActivity.this);
			break;
		// YUHANXUN
		case R.id.check_appver_btn:
			if (DealHttp.isConnectInternet(this)) {
				// if (AppGlobalVariable.hasSDCard())
				startCheckVerThread();
				// else
				// Toast.makeText(MainActivity.this, "未检测到SD卡，更新失败",
				// Toast.LENGTH_SHORT).show();
			} else
				Toast.makeText(MainActivity.this, "当前网络不可用", Toast.LENGTH_SHORT).show();
			break;
		}
	}

	// YUHANXUN
	public boolean startGetLocalAddress() {
		if (AppGlobalVariable.hasSDCard()) {
			String path = AppGlobalVariable.getSDcard_DOWNLOAD() + AppGlobalVariable.ADDRESS_LOCAL_FILE_NAME;
			String txtContext = DealFile.ReadTxtFile(path);
			if (txtContext.equals(""))
				return false;
			else {
				String ret2[] = txtContext.split("\n");
				for (int i = 0; i < ret2.length; i++) {
					ret2[i] = ret2[i].replaceAll("\\s*", "");
					ret2[i] = ret2[i].replaceAll("\0", "");
				}
				sUrlList = ret2;
				return true;
			}
		} else {
			return false;
		}
	}

	// YUHANXUN
	public void startGetAddressThread() {
		new Thread(new Runnable() {
			@Override
			public void run() {
				// TODO Auto-generated method stub
				String[] ret = MyDownloadToolHttp.getAddress(Address_URL);
				if (ret != null) {
					sUrlList = ret;
					checkVerHandler.obtainMessage(GET_ADDRESS_WEB_OK).sendToTarget();
				} else {
					checkVerHandler.obtainMessage(GET_ADDRESS_WEB_FAIL).sendToTarget();
				}
			}
		}).start();
	}

	// YUHANXUN
	public void startCheckVerThread() {
		new Thread(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				CheckVersionBean cvb = MyDownloadToolHttp.getVersion(CHECK_APP_VER_URL);
				if (cvb != null)
					checkVerHandler.obtainMessage(START_CHECK, cvb).sendToTarget();
				else
					checkVerHandler.obtainMessage(NETWORK_ERROR).sendToTarget();
				return;
			}
		}).start();
	}

	// YUHANXUN
	public void startCheckVerDownloadThread(final String url) {
		new Thread(new Runnable() {
			@Override
			public void run() {
				// TODO Auto-generated method stub
				String filePath = AppGlobalVariable.getDIR_DOWNLOAD() + url.substring(url.lastIndexOf("/") + 1, url.length());
				if (DealHttp.downloadFile(url, filePath, null, new ProgressControl() {
					@Override
					public void stepControl(final double i) {
						checkVerHandler.post(new Runnable() {
							@Override
							public void run() {
								// TODO Auto-generated method stub
								mProgressBar.setProgress((int) i);
								mProgressBar.setVisibility(View.VISIBLE);
							}
						});
					}

					@Override
					public void messageControl(String str) {
					}
				})) {
					checkVerHandler.post(new Runnable() {
						@Override
						public void run() {
							mProgressBar.setVisibility(View.GONE);
							checkVerHandler.obtainMessage(START_INSTALL, url).sendToTarget();
						}
					});
				}
			}
		}).start();
	}

	// 开始
	Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case START_THREAD:
				mService.closeRtsp();
				String text = mThreadNumber.getText().toString().trim();
				mTotalDataString = mTotalDataEditText.getText().toString().trim();
				if (!TextUtils.isEmpty(text) && !TextUtils.isEmpty(mTotalDataString)) {
					if (isRunning) {
						mMaxData = Long.parseLong(mTotalDataString) * 1048576;
						mService.setupRtsp(sUrlList[mUrlPoint], Integer.parseInt(text));
						mUrlPoint = (mUrlPoint + 1) % sUrlList.length;
						
						//重连时间
						handler.sendMessageDelayed(handler.obtainMessage(), 1 * 60 * 1000);
					}
				} else {
					Toast.makeText(MainActivity.this, "请输入正确的线程数或者下载总量！", Toast.LENGTH_SHORT).show();
				}
				break;
			case CACULATE_DATA:
				setResultView(mDownloadData);
				handler.sendEmptyMessageDelayed(CACULATE_DATA, 1000);
				break;
			case HAND_OFF:
				try {
					iTelephony.endCall();
				} catch (RemoteException e) {
					e.printStackTrace();
				}

				break;
			case USE_TIME:
				mUseTimeTextView.setText(" 已下载：" + mDownloadTime + "分钟");
				break;
			}
		}
	};
	// YUHANXUN
	Handler checkVerHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case START_CHECK:
				final Object obj = msg.obj;
				double localVer = Double.parseDouble(AppGlobalVariable.getAppVersionName(MainActivity.this));
				double currentVer = Double.parseDouble(((CheckVersionBean) msg.obj).version);
				// 1023修改成只要版本号不同则提示更新
				if (currentVer != localVer) {
					new AlertDialog.Builder(MainActivity.this).setIcon(android.R.drawable.ic_dialog_alert).setTitle("确认").setMessage("是否下载更新?")
							.setPositiveButton("是", new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog, int which) {
									checkVerHandler.obtainMessage(START_DOWNLOAD, obj).sendToTarget();
								}
							}).setNegativeButton("否", null).show();
				} else {
					Toast.makeText(MainActivity.this, "版本已是最新", Toast.LENGTH_SHORT).show();
				}
				break;
			case START_DOWNLOAD:
				startCheckVerDownloadThread(((CheckVersionBean) msg.obj).apkAddUrl);
				break;
			case START_INSTALL:
				String url = (String) msg.obj;
				String apkPath = AppGlobalVariable.getDIR_DOWNLOAD() + url.substring(url.lastIndexOf("/") + 1, url.length());
				String[] args2 = { "chmod", "777", apkPath };
				AppGlobalVariable.exec(args2);
				DealFile.openFile(new File(apkPath), MainActivity.this);
				break;
			case NETWORK_ERROR:
				Toast.makeText(MainActivity.this, "无法获取更新信息", Toast.LENGTH_SHORT).show();
				break;

			case GET_ADDRESS_WEB_OK:
				Toast.makeText(MainActivity.this, "已从服务器获取链接地址" + sUrlList.length, Toast.LENGTH_SHORT).show();
				break;

			case GET_ADDRESS_WEB_FAIL:
				Toast.makeText(MainActivity.this, "无法获取链接地址,使用默认链接", Toast.LENGTH_SHORT).show();
				break;

			case GET_ADDRESS_LOCAL_OK:
				Toast.makeText(MainActivity.this, "已从本地获取链接地址" + sUrlList.length, Toast.LENGTH_SHORT).show();
				break;
			}
		}
	};

	// @Override
	// public boolean onCreateOptionsMenu(Menu menu) {
	// getMenuInflater().inflate(R.menu.activity_main, menu);
	// return true;
	// }

	// YUHANXUN
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			new AlertDialog.Builder(this).setIcon(android.R.drawable.ic_dialog_alert).setTitle("退出").setMessage("是否要退出程序?")
					.setPositiveButton("是", new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							DDebug.logd("back yes");
							isRunning = false;
							mService.closeRtsp();
							if (isRegister) {
								unregisterReceiver(mTimeReceiver);
								isRegister = false;
							}
							DealFile.delAllFile(AppGlobalVariable.getDIR_DOWNLOAD());
							MainActivity.this.finish();
						}
					}).setNegativeButton("否", null).show();
			return true;
		} else {
			return super.onKeyDown(keyCode, event);
		}
	}

	// YUHANXUN
	public void uninstall(Context context, final String packageName) {
		if (AppGlobalVariable.hasThatApk(context, packageName)) {
			Toast.makeText(context, "注意：几秒后会提示卸载旧版应用，请选择卸载，谢谢", Toast.LENGTH_LONG).show();
			handler.postDelayed(new Runnable() {
				@Override
				public void run() {
					// TODO Auto-generated method stub
					Uri packageURI = Uri.parse("package:" + packageName);
					Intent uninstallIntent = new Intent(Intent.ACTION_DELETE, packageURI);
					startActivityForResult(uninstallIntent, UNINSTALL_REQUEST);
				}
			}, 5000);
		}
	}

}
